# @Time : 2024-11-07 13:37
# @Author : Fioman 
# @Phone : 13149920693
"""
IO计算: 由于Python会释放GIL锁,不存在GIL锁的问题,而线程的创建和销毁开销比进程的少,所以使用多线程比
使用多进程的效率和速度要快很多
"""
import time
from concurrent.futures import ThreadPoolExecutor, wait, ProcessPoolExecutor


def task_delay(n, seconds):
    print(f"task {n} 开始")
    time.sleep(seconds)
    print(f"task {n} 结束")
    return f"task {n}"


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=50) as executor:
        startTime = time.time()
        futures = [executor.submit(task_delay, i, 2) for i in range(50)]
        wait(futures)  # 等待所有的线程执行完毕
        print("线程耗时: {}".format(time.time() - startTime))  # 线程耗时: 2.006122350692749

    with ProcessPoolExecutor(max_workers=50) as executor:
        startTime = time.time()
        futures = [executor.submit(task_delay, i, 2) for i in range(50)]
        wait(futures)
        print("进程耗时: {}".format(time.time() - startTime))  # 进程耗时: 3.8432796001434326

    """
    进程创建的越多,越耗时,而线程创建的时间就可以忽略不计,所以如果是非必要,不要使用多进程,只有计算量比较大
    的地方才会需要多进程.
    """
